package iso3.pt.action;

import iso3.pt.dao.IncorrectPasswordException;
import iso3.pt.dao.UserNotFoundException;
import iso3.pt.model.Alumno;
import iso3.pt.model.Profesor;
import iso3.pt.service.PtDaoService;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;

public class LoginAction extends com.opensymphony.xwork2.ActionSupport implements com.opensymphony.xwork2.Preparable {

	private static final long serialVersionUID = 1L;
	
	private int username;
	private String password;
	private String userType;
	private Alumno student;
	private Profesor lecturer;

	@Override
	public void prepare() throws Exception {
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String doLogin() throws Exception {
		/* Prepare session and get PtService */
		Map session = ActionContext.getContext().getSession();
		PtDaoService daoService = new PtDaoService();
		/* Working with user types */
		if(this.getUserType().equals("Profesor")) {
			try {
				Profesor prof = daoService.loginProfesor(this.getUsername(), this.getPassword());
				session.put("user", prof);
				return "loginLecturer";
			} catch (UserNotFoundException e) {
				addActionError("User not found");
	            return ERROR;
			} catch (IncorrectPasswordException e) {
				addActionError("Incorrect password");
	            return ERROR;
			} catch (Exception e) {
				return ERROR;
			}
		}
		else {
			try {
				Alumno alumno = daoService.loginAlumno(this.getUsername(), this.getPassword());
				session.put("user", alumno);
				return "loginStudent";
			} catch (UserNotFoundException e) {
				addActionError("User not found");
	            return ERROR;
			} catch (IncorrectPasswordException e) {
				addActionError("Incorrect password");
	            return ERROR;
			} catch (Exception e) {
				return ERROR;
			}
		}
	}
	
	public String doLogout() {
		// TODO Auto-generated method stub
		
		return null;
	}
	
	public int getUsername() {
		return username;
	}
	
	public void setUsername(int user) {
		this.username = user;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String pass) {
		this.password = pass;
	}
	
	public String getUserType() {
		return userType;
	}
	
	public void setUserType(String userType) {
		this.userType = userType;
	}
	
	public Alumno getStudent() {
		return student;
	}
	
	public void setStudent(Alumno student) {
		this.student = student;
	}
	
	public Profesor getLecturer() {
		return lecturer;
	}
	
	public void setLecturer(Profesor lecturer) {
		this.lecturer = lecturer;
	}
}
